﻿using System.Collections;
using System.Reflection;

namespace zijian666.Core;

/// <summary>
/// 程序集集合
/// </summary>
public partial class AssemblyCollection : IEnumerable<(Assembly, Type[])>
{
    private readonly ConcurrentList<AssemblyDescription> _descriptions = new(null);

    /// <summary>
    /// 程序集数量
    /// </summary>
    public int Count => _descriptions.Count;

    /// <inheritdoc />
    IEnumerator<(Assembly, Type[])> IEnumerable<(Assembly, Type[])>.GetEnumerator() => _descriptions.Select(x => (x.Assembly, x.Types)).GetEnumerator();

    /// <inheritdoc />
    IEnumerator IEnumerable.GetEnumerator() => _descriptions.Select(x => (x.Assembly, x.Types)).GetEnumerator();

    /// <summary>
    /// 是否包含指定的程序集
    /// </summary>
    public bool Contains(Assembly assembly) => _descriptions.Contains(x => x.Assembly == assembly);

    /// <summary>
    /// 添加程序集到集合, 如果已经存在返回false
    /// </summary>
    public bool Add(Assembly assembly) => _descriptions.Add(new(assembly));

    /// <summary>
    /// 添加一组程序集到集合, 返回添加成功的数量
    /// </summary>
    /// <param name="assemblies"></param>
    public int AddRange(IEnumerable<Assembly> assemblies)
    {
        var i = 0;
        foreach (var assembly in assemblies)
        {
            if (assembly is not null && _descriptions.Add(new(assembly)))
            {
                i++;
            }
        }
        return i;
    }
}
